package org.kiwi.job.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.concurrent.TimeUnit;

/**
 * @email jack.liu.19910921@gmail.com
 * Created by jack on 17/2/19.
 */
@Component
public class LockTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(LockTemplate.class);

    @Autowired
    private RedisCacheManager cacheManager;

    public boolean lock(String lockKey) {
        return lock(lockKey, 10 * 1000l);
    }

    public boolean lock(String lockKey, long maxMillis) {
        lockKey = cacheManager.getCacheKey(lockKey);
        long currentTimeMillis = System.currentTimeMillis();
        long lockTimeout = currentTimeMillis + maxMillis + 1;
        boolean result = cacheManager.setNX(lockKey, lockTimeout);
        if (!result) {
            long existsTimeout = cacheManager.get(lockKey, Long.class);
            if (existsTimeout < currentTimeMillis) {
                return cacheManager.getAndSet(lockKey, lockTimeout) < currentTimeMillis;
            }
        }
        return result;
    }

    public void unLock(String lockKey) {
        long existsTimeout = cacheManager.get(lockKey, Long.class);
        if (existsTimeout > System.currentTimeMillis()) {
            cacheManager.delete(lockKey);
        }
    }

    public boolean tryLock(String lockKey) {
        return cacheManager.setNX(lockKey, System.currentTimeMillis());
    }

    public boolean tryLock(String lockKey, long timeout, TimeUnit timeUnit) {
        return cacheManager.setNX(lockKey, System.currentTimeMillis(), timeout, timeUnit);
    }

    public void release(final String lockKey) {
        try {
            if (TransactionSynchronizationManager.isSynchronizationActive()) {
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    @Override
                    public void beforeCommit(boolean readOnly) {
                        cacheManager.delete(lockKey);
                    }
                });
            } else {
                cacheManager.delete(lockKey);
            }
        } catch (Exception e) {
            LOGGER.info("释放锁失败,异常信息:【{}】", e.getMessage());
        }
    }

}
